package com.qys.fileservlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.springframework.web.multipart.MultipartFile;

import com.qys.fileservice.fileService;

@WebServlet("/upload")
@MultipartConfig
public class fileServlet extends HttpServlet{
	MultipartFile file;
	
	private fileService service = new fileService();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			Part part=req.getPart("file");
			String disposition = part.getHeader("Content-Disposition");
			String filename = disposition.substring(disposition.indexOf("filename=\"") + 10, disposition.lastIndexOf("\""));
			LocalDate date = LocalDate.now();
			int month = date.getMonthValue();
			int today = date.getDayOfMonth();
			String addFile = "E:\\qiyuesuo\\"+month+"月"+today+"日";
			File file = new File(addFile);
			file.mkdir();
			
			 try { 
				service.upFile(filename);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			 
			 InputStream is = part.getInputStream();
			 FileOutputStream fos = new FileOutputStream(addFile+"/"+filename); 
			 byte[] bty = new byte[1024];
		        int length =0;
		        while((length=is.read(bty))!=-1){
		            fos.write(bty,0,length);
		        }
				 
		        fos.close();
		        is.close();  
			System.out.println("上传成功，文件名为："+filename+"。已经存入数据库");
			System.out.println("自动生成文件夹成功，文件日期为："+month+"月"+today+"日");

	}
}


